﻿using UnityEngine;
using UnityGameFramework.Runtime;

namespace Adventure
{
    /// <summary>
    /// 游戏存档组件
    /// </summary>
    public class ArchiveComponent : GameFrameworkComponent
    {

        /// <summary>
        /// 游戏存档文件
        /// </summary>
        private string GameDataFileName { get; set; }

        #region 需要存档的游戏数据

        /// <summary>
        /// 需要存档的游戏数据
        /// </summary>
        [field: SerializeField]
        public GameData Data { get; private set; }

        #endregion

        protected override void Awake()
        {
            base.Awake();
            Data = new GameData(SystemInfo.deviceUniqueIdentifier);
        }

        public string GetFullFilePath()
        {            
            return Application.persistentDataPath + GameDataFileName;
        }

        /// <summary>
        /// 设置加载那个账号数据
        /// </summary>
        /// <param name="arg1"></param>
        public void SetUserLoadPath(string arg1) 
        {
            GameDataFileName = "/" + arg1 + ".dat";
        }

        /// <summary>
        /// 存档时调用
        /// </summary>
        public void Save()
        {
            IOHelper.SetData(GetFullFilePath(), Data);
            Log.Debug($"更新存档, path:{GetFullFilePath()}");
        }

        /// <summary>
        /// 读档时调用
        /// </summary>
        /// <returns>是否读取存档成功</returns>
        public bool Load(string arg)
        {
            if (arg == Constant.Setting.UserData)
            {
                arg = GameEntry.Setting.GetString(Constant.Setting.UserData, "");
            }
            SetUserLoadPath(arg);

            if (IOHelper.IsFileExists(GetFullFilePath()))
            {
                var gameData = IOHelper.GetData(GetFullFilePath());
                if (gameData != null && gameData.Key.Equals(Data.Key))
                {
                    Data = gameData;
                    Log.Debug($"读取存档成功，合法存档, path:{GetFullFilePath()}");
                    return true;
                }

                Log.Debug($"读取存档失败，非法存档, path:{GetFullFilePath()}");
                return false;
            }

            Log.Debug($"读取存档失败，存档不存在, path:{GetFullFilePath()}");
            return false;
        }

    }
}